package com.whmall.service.crm.module.openapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.whmall.component.service.AbstractDbService;
import com.whmall.component.util.function.CheckedExWrapper;
import com.whmall.service.crm.entity.dto.openapi.OpenPlatformAppQueryReqDTO;
import com.whmall.service.crm.entity.dto.openapi.OpenPlatformAppRspDTO;
import com.whmall.service.crm.module.openapi.dao.OpenPlatformAppDOMapper;
import com.whmall.service.crm.module.openapi.entity.OpenPlatformAppDO;
import com.whmall.service.crm.module.openapi.service.OpenPlatformAppService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class OpenPlatformAppServiceImpl extends AbstractDbService<OpenPlatformAppDOMapper, OpenPlatformAppDO> implements OpenPlatformAppService {

    private final ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public OpenPlatformAppRspDTO queryInfoByAppID(String appId) {
        if (StrUtil.isEmpty(appId)) {
            throw new IllegalArgumentException("appId不能为空");
        }
        OpenPlatformAppDO openPlatformAppDO = this.lambdaQuery().eq(OpenPlatformAppDO::getAppId, appId)
                .eq(OpenPlatformAppDO::getIsEnabled, 1)
                .eq(OpenPlatformAppDO::getDeleted, 0)
                .one();
        if (openPlatformAppDO == null) {
            return null;
        }
        OpenPlatformAppRspDTO openPlatformAppRspDTO = new OpenPlatformAppRspDTO();
        BeanUtils.copyProperties(openPlatformAppDO, openPlatformAppRspDTO, "property");
        openPlatformAppRspDTO.setProperty(objectMapper.readValue(openPlatformAppDO.getProperty(), OpenPlatformAppRspDTO.Property.class));
        return openPlatformAppRspDTO;
    }

    @Override
    public List<OpenPlatformAppRspDTO> selectBy(OpenPlatformAppQueryReqDTO queryReqDTO) {
        if (queryReqDTO == null || CollUtil.isEmpty(queryReqDTO.getIdIn())) {
            return new ArrayList<>();
        }
        List<OpenPlatformAppDO> openPlatformAppDOS = this.lambdaQuery().in(OpenPlatformAppDO::getId, queryReqDTO.getIdIn())
                .eq(OpenPlatformAppDO::getDeleted, 0)
                .list();
        if (CollUtil.isNotEmpty(openPlatformAppDOS)) {
            return openPlatformAppDOS.stream().map(d -> BeanUtil.copyProperties(d, OpenPlatformAppRspDTO.class, "property")
                            .setProperty(CheckedExWrapper.supplier(() -> objectMapper.readValue(d.getProperty(), OpenPlatformAppRspDTO.Property.class))))
                    .collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}
